<?php
/**
 * Silverstripe Dashboard Panels 
 * TODO Dynamic Panels Title
 * TODO Display only the colunms number; if more data at the SSPanelsData Table shold not be displayed
 * TODO Control the javascript files to load
 * TODO Error check
 * @author rgodinho
 */
class SSPanels extends Extension {
	
	/**
	 * Number of columns
	 * @var integer
	 */
	public static $colNumber = 6;
	
	/**
	 * To save or not to save the panels configuration
	 * for anonymous users
	 * TODO To Implement 
	 * @var booleam 
	 */
	public static $save_anonymous_state = false;
	
	/**
	 * Panel data.
	 * The array data position fills the panels
	 * If null display dummy data
	 * @example SSPanels::$panelData[0] = 'The content for the panel 0';   
	 * @var array
	 */
	public static $panelData = array();
	
	/**
	 * Panel Titles
	 * Can be used to show dynamic titles
	 * Another option is to change the title table records
	 * @var array
	 */
	public static $panelTitle = array();
	
	/**
	 * Dummy data for the panels
	 * Change the value at the _config.php project file
	 * TODO Lang file translation
	 * @var string
	 */
	public static $dummyData = 'Dummy Data...';
	
	function extraStatics() { 
		return array(); 
	}

	public function Subject() {
		return $this->owner;
	}
		
	protected function createPanelData($userID) {
		if(!DataObject::get('SSPanelsData', "SSPanelsData.user_id = $userID")) {	
			for($i= 0; $i < SSPanels::$colNumber; $i++) {
				$panels = new SSPanelsData();
				$panels->write();
				$panels->column_id = $i % 2;
				$panels->sort_no = 1;
				$panels->collapsed= 0;
				$panels->title = 'Panel ' . $i;
				$panels->user_id = $userID;
				$panels->panel_id = $i;
				$panels->write();
			}
		}				
	}

   /**
   * Get Dashboard
   * @return html rendered
   */
  public function getDashboard() {

		Requirements::javascript(SSPANELS . '/javascript/jquery-1.3.2.js');
		Requirements::javascript(SSPANELS . '/javascript/jquery-ui-1.7.2.custom.min.js');
		Requirements::javascript(SSPANELS . '/javascript/sspanels.js');
		Requirements::javascript(SSPANELS . '/javascript/jquery.json-2.2.min.js');
		
		// -- Extension css file
		$this->includePluginsCss('sspanels.css');

    	return $this->owner->renderWith('SSPanels');
	}

	/**
	 * Get panels data
	 * @return DataObject
	 */
	public function getPanels() {
		$userID = Member::currentUserID();
		
		// -- need to check if exist panel data for the user
		$this->createPanelData($userID);
		
		$columns=DB::query('SELECT DISTINCT column_id FROM SSPanelsData where user_id = ' . $userID . ' ORDER BY column_id');

		$htmlPanels = '';		
		
		foreach($columns as $col) {
			$htmlPanels .= '<div class="column" id="column'.$col['column_id'].'" >';

			$items=DB::query("SELECT * FROM SSPanelsData WHERE column_id='".$col['column_id']."' and user_id = ' . $userID . ' ORDER BY sort_no");

			foreach($items as $widget)
			{
				if (!array_key_exists($widget['panel_id'], self::$panelData)) {
					self::$panelData[$widget['panel_id']] = self::$dummyData;
				}
				
				$pTitle = $widget['title'];
				
				if (array_key_exists($widget['panel_id'], self::$panelTitle)) {
					$pTitle = self::$panelTitle[$widget['panel_id']];
				}				
				
				$htmlPanels .= '
				<div class="dragbox" id="item'.$widget['ID'].'">
					<h2>'. $pTitle . '</h2>
						<div class="dragbox-content" ';
				if($widget['collapsed']==1)
					$htmlPanels .= 'style="display:none;" ';
					$htmlPanels .= '>'. self::$panelData[$widget['panel_id']] .'
						</div>
				</div>';
			}
			$htmlPanels .= '</div>';			
			
		}		
		return $htmlPanels;
	}
  
  /**
   * include a css, check first in the the theme, then project, in the module or jsparty treeview
   * @param $css
   * @return void
   */
  private function includePluginsCss( $css ) {
    if( Director::fileExists($file = project() . '/themes/' . SSViewer::current_theme() . '/css/' . $css) ) {
      Requirements::css($file);

    }
    elseif( Director::fileExists($file = project() . '/css/' . $css) ) {
      Requirements::css($file);
    }
    elseif( Director::fileExists($file = SSPANELS . '/css/' . $css) )  {    	
      Requirements::css(SSPANELS . '/css/' . $css);
    }
    else {
    	// -- TODO
    }
  }  
}

class SSPanels_Controller extends Page_Controller {    
    /**
     * Save Panels Position
     * @return void
     */
	function savepanels() {		
		if(!$_POST["data"]){
			echo "Invalid data";
			exit;
		}

		//decode JSON data received from AJAX POST request
		$data=json_decode($_POST["data"]);

		foreach($data->items as $item)
		{
			//Extract column number for panel
			$col_id=preg_replace('/[^\d\s]/', '', $item->column);

			//Extract id of the panel
			$widget_id=preg_replace('/[^\d\s]/', '', $item->id);
			
			$userID = Member::currentUserID();
		
			DB::query("UPDATE SSPanelsData SET column_id='$col_id', sort_no='".$item->order."', collapsed='".$item->collapsed."' WHERE id='".$widget_id."' AND user_id = $userID");
		}
		echo "success";		
	}
}